import {
  articleCollectAPI,
  articleDislikeAPI,
  articleLikingAPI,
  articleReportAPI,
  cancelArticleCollectAPI,
  cancelArticleLikingAPI,
  getArticleDetailAPI,
  getArticleListAPI,
} from '@/api/articleList';
import store, { AppDispatch } from '@/store/index';
import { ArticlesAction } from '../reducer/articleList';

export function articleListActionCreator({
  channel_id = 0,
  timestamp = Date.now(),
  isRefresh = false,
}) {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleListAPI({
      channel_id,
      timestamp,
    });
    // console.log(20, res);
    // 获取原来的articles数据
    const { articles } = store.getState().articleList;
    // console.log(11, articles);

    // 获取当前频道的新闻列表，可能获取到undefined，或者[]
    const list = articles[channel_id]?.list;
    const pre_timestamp = res.data.pre_timestamp;

    if (!list || isRefresh) {
      // 1.没有列表，直接存
      dispatch({
        type: 'article/saveArticles',
        payload: {
          ...articles,
          [channel_id]: {
            timestamp: pre_timestamp,
            list: res.data.results,
          },
        },
      });
    } else {
      // 如果有新列表（上拉加载下一页数据的话，把新值和旧值拼接在一起）
      dispatch({
        type: 'article/saveArticles',
        payload: {
          ...articles,
          [channel_id]: {
            timestamp: pre_timestamp,
            list: [...list, ...res.data.results],
          },
        },
      });
    }
    if (!pre_timestamp) {
      return Promise.reject('没有推荐了');
    }
  };
}

// 文章标记
export function setArticleMarkActionCreator({
  visible = false,
  article_id = '',
}): ArticlesAction {
  return {
    type: 'article/setMark',
    payload: { visible, article_id },
  };
}

// 文章不感兴趣
export function setArticleDislikeActionCreator(id: string) {
  return async (dispatch: AppDispatch) => {
    // 发送请求让后端更新文章变为不i喜欢
    const res = await articleDislikeAPI(id);
    // console.log(72, res);
    // 获取当前频道 id
    const activeId = store.getState().channel.activeId;
    // // 根据频道 id 获取文章列表
    const articles = store.getState().articleList.articles;
    // const { channel: { activeId }, article: { articles } } = store.getState()
    // 根据频道 id 获取文章列表
    const { list, timestamp } = articles[activeId];
    dispatch({
      type: 'article/saveArticles',
      payload: {
        // 保留其他频道的数据
        ...articles,
        // 当前频道的不喜欢的那条文章过滤掉
        [activeId]: {
          timestamp,
          list: list.filter((v) => v.art_id !== id),
        },
      },
    });
  };
}

// 举报文章
export function setArticleReportActionCreator({
  target,
  type,
  remark,
  activeId,
}: {
  target: string;
  type: string;
  remark: string;
  activeId: number;
}) {
  return async (dispatch: AppDispatch) => {
    const res = await articleReportAPI({ target, type, remark });
    console.log(101, res);
    console.log(113, activeId);

    dispatch({
      type: 'article/setArticleReport',
      payload: { target, type, remark, activeId },
    });
  };
}

// 获取文章详情
export function getArticleActionCreator(id: string) {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleDetailAPI(id);
    // console.log(127, res);
    dispatch({
      type: 'article/articleDetail',
      payload: res.data,
    });
  };
}

// 对文章点赞和取消点赞
export function changeArticleLikingAction(target: string, attitude: number) {
  return async (dispatch: AppDispatch) => {
    // 点赞
    if (attitude === 1) {
      await articleLikingAPI(target);
      dispatch({
        type: 'article/changeArticleDetailLiking',
        payload: { target, attitude },
      });
    } else {
      await cancelArticleLikingAPI(target);
      dispatch({
        type: 'article/changeArticleDetailLiking',
        payload: { target, attitude },
      });
    }
  };
}

// 收藏文章和取消收藏文章
export function changeArticleCollectAction(target: string, collect: boolean) {
  return async (dispatch: AppDispatch) => {
    // 收藏
    if (collect) {
      await articleCollectAPI(target);
      dispatch({
        type: 'article/changeArticleDetailCollect',
        payload: { target, collect },
      });
    } else {
      await cancelArticleCollectAPI(target);
      dispatch({
        type: 'article/changeArticleDetailCollect',
        payload: { target, collect },
      });
    }
  };
}
